
import sqlite3


import time 
import hashlib
import requests
import uuid
import json

class youdaoapi():

    def __init__(self) -> None:
        self.url = 'https://openapi.youdao.com/api'
        self.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        self.app_key = '552d0c75e3cd6ac3'
        self.app_secret = 'pDYwwZOupJNxEQIRWT9cYcg6xx0gp24z'

    def query(self, word):
        data = {}
        data['from'] = 'auto'
        data['to'] = 'auto'
        data['signType'] = 'v3'
        curtime = str(int(time.time()))
        data['curtime'] = curtime
        salt = str(uuid.uuid1())
        signStr = self.app_key + self.truncate(word) + salt + curtime + self.app_secret
        sign = self.encrypt(signStr)
        data['appKey'] = self.app_key
        data['q'] = word
        data['salt'] = salt
        data['sign'] = sign
        # data['vocabId'] = "您的用户词表ID" 

        resonse = requests.post(self.url, data=data, headers=self.headers)
        content_type = resonse.headers['Content-Type']
        if content_type == 'audio/mp3':
            pass
        else:
            return resonse.content

    def truncate(self, q):
        if q is None:
            return ''
        size = len(q)
        return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]

    def encrypt(self, signStr):
        hash_algorithm = hashlib.sha256()
        hash_algorithm.update(signStr.encode('utf-8'))
        return hash_algorithm.hexdigest()

yd = youdaoapi()
rs = yd.query("hello")
rs.decode("utf-8")
t = json.loads(rs)
print(t)

# ret = ret.decode("utf-8")
# t = json.loads(ret)
# print(type(t))
# print(t['errorCode'])
# print(t['basic']['explains'])



